<template>
  <div class="app-container">
    <div class="main-content">
      <div class="main-box">
        <h1 class="title">助手中心</h1>

        <div class="large-textarea">
          <textarea
            v-model="searchQuery"
            placeholder='请描述你的 Agent 任务需求，比如："创建一个智能助手，帮助我规划旅行行程..."'
            class="textarea-input"
            rows="4"
          ></textarea>
          <button class="search-button" @click="handleSearch">⬆️</button>
        </div>

        <!-- 分类标签 -->
        <div class="tabs">
          <button
            v-for="tab in tabs"
            :key="tab"
            @click="activeTab = tab"
            :class="['tab-button', { active: activeTab === tab }]"
          >
            {{ tab }}
          </button>
        </div>

        <!-- 卡片展示区 -->
        <div class="cards">
          <div v-if="loading" class="loading">加载中...</div>
          <div
            v-else-if="filteredCards.length === 0"
            class="no-result"
          >
            暂无结果，请尝试其他搜索。
          </div>
          <div
            v-else
            v-for="card in filteredCards"
            :key="card.text"
            class="card"
          >
            <p class="card-text">{{ card.text }}</p>
            <div class="card-source">来源：{{ card.source }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧状态监控栏 -->
    <div class="status-sidebar">
      <div class="task-status-header">
        <h3>任务监控</h3>
        <span class="task-count">{{ tasks.length }} 个任务</span>
      </div>
      
      <div class="task-list">
        <div v-if="tasks.length === 0" class="no-tasks">
          暂无任务
        </div>
        <div
          v-for="task in tasks"
          :key="task.id"
          class="task-item"
          :class="{ 'task-active': task.status === 'running' }"
        >
          <div class="task-item-header">
            <span :class="['status-badge', task.status]">{{ getStatusText(task.status) }}</span>
            <button class="delete-task" @click="deleteTask(task.id)">×</button>
          </div>
          <div class="task-item-content">
            <p class="task-description">{{ task.description }}</p>
            <div class="task-details">
              <p>ID: {{ task.id }}</p>
              <p>开始: {{ formatTime(task.startTime) }}</p>
              <p v-if="task.endTime">完成: {{ formatTime(task.endTime) }}</p>
            </div>
            <div class="progress-bar" v-if="task.status === 'running'">
              <div class="progress" :style="{ width: task.progress + '%' }"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import axios from 'axios';
// 中文分类标签
const tabs = [
  '用餐与活动',
  '配送',
  '本地服务',
  '购物',
  '旅行',
  '新闻',
]

const activeTab = ref('购物')
const searchQuery = ref('')
const loading = ref(false)

const cards = ref([
  {
    tab: '购物',
    text: '帮我找一个 100 元以内的空气炸锅',
    source: '京东',
  },
  {
    tab: '购物',
    text: '有没有可以定制家族姓氏的乡村风格厨房装饰？',
    source: '淘宝',
  },
])

// 任务列表
const tasks = ref([])

const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '等待中',
    'IN_PROGRESS': '执行中',
    'COMPLETED': '已完成',
    'FAILED': '失败',
    'running': '执行中',  // 添加小写状态映射
    'completed': '已完成',
    'failed': '失败'
  }
  return statusMap[status] || status
}

const formatTime = (timestamp) => {
  if (!timestamp) return '未开始'
  return new Date(timestamp).toLocaleString()
}

const deleteTask = (taskId) => {
  tasks.value = tasks.value.filter(task => task.id !== taskId)
}

const handleSearch = async () => {
  if (!searchQuery.value.trim()) return

  loading.value = true
  
  // 创建新任务
  const newTask = {
    id: null,
    status: 'PENDING',
    startTime: new Date(),
    progress: 0,
    description: searchQuery.value
  }
  
  // 添加到任务列表
  tasks.value.unshift(newTask)

  try {
    const response = await axios.post('http://localhost:8080/task/submit', {
      name: `Task ${Date.now()}`,
      description: searchQuery.value
    })
    
    console.log('Submit response:', response.data)  // 添加日志
    
    // 更新任务ID和状态
    const taskIndex = tasks.value.findIndex(t => t.id === newTask.id)
    if (taskIndex !== -1) {
      // 确保response.data包含所需的所有字段
      const taskData = {
        id: response.data.taskId,
        status: (response.data.status || 'PENDING').toUpperCase(),
        description: response.data.description || searchQuery.value,
        startTime: new Date(),
        progress: 0,
        createdAt: response.data.createdAt || new Date(),
        updatedAt: response.data.updatedAt || new Date()
      }
      
      // 更新任务数据
      tasks.value[taskIndex] = taskData
      
      // 开始轮询任务状态
      pollTaskStatus(taskData.id, taskIndex)
    }

    // 更新卡片内容
    cards.value = [
      {
        tab: activeTab.value,
        text: response.data.description || searchQuery.value,
        source: '系统',
      },
    ]
  } catch (error) {
    console.error('请求失败:', error)
    // 更新任务状态为失败
    const taskIndex = tasks.value.findIndex(t => t.id === newTask.id)
    if (taskIndex !== -1) {
      tasks.value[taskIndex].status = 'FAILED'
      tasks.value[taskIndex].endTime = new Date()
    }
    
    cards.value = [
      {
        tab: activeTab.value,
        text: '❌ 请求失败，请检查网络或后端服务。',
        source: '系统',
      },
    ]
  } finally {
    loading.value = false
  }
}

// 轮询任务状态的函数
const pollTaskStatus = async (taskId, taskIndex) => {
  const pollInterval = setInterval(async () => {
    try {
      const response = await axios.get(`http://localhost:8080/task/${taskId}`)
      const taskStatus = response.data
      
      // 更新任务状态
      if (taskIndex !== -1 && tasks.value[taskIndex]) {
        // 统一状态格式
        const status = taskStatus.status.toUpperCase()
        tasks.value[taskIndex].status = status
        tasks.value[taskIndex].updatedAt = taskStatus.updatedAt
        
        // 如果任务完成或失败，停止轮询
        if (status === 'COMPLETED' || status === 'FAILED') {
          clearInterval(pollInterval)
          tasks.value[taskIndex].endTime = new Date(taskStatus.updatedAt)
          
          // 如果任务完成，更新卡片内容
          if (status === 'COMPLETED') {
            cards.value = [
              {
                tab: activeTab.value,
                text: taskStatus.description || '任务已完成',
                source: '系统',
              },
            ]
          }
        }
      }
    } catch (error) {
      console.error('获取任务状态失败:', error)
      clearInterval(pollInterval)
      if (taskIndex !== -1 && tasks.value[taskIndex]) {
        tasks.value[taskIndex].status = 'FAILED'
        tasks.value[taskIndex].endTime = new Date()
      }
    }
  }, 2000) // 每2秒轮询一次
}

const filteredCards = computed(() =>
  cards.value.filter((c) => c.tab === activeTab.value)
)
</script>

<style>
body {
  margin: 0;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background: linear-gradient(to right, #e8f4ff, #f1f8ff);
  min-height: 100vh;
  overflow-x: hidden;
}

.app-container {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;
  padding: 40px 20px;
  min-height: 100vh;
  max-width: 1400px;
  margin: 0 auto;
  box-sizing: border-box;
}

.main-content {
  width: 100%;
  overflow: hidden;
}

.main-box {
  background-color: white;
  border-radius: 24px;
  width: 100%;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.title {
  text-align: center;
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 30px;
}

.large-textarea {
  position: relative;
  margin-bottom: 20px;
}

.textarea-input {
  width: 100%;
  border: 1px solid #e0e0e0;
  background: #fff;
  font-size: 16px;
  resize: vertical;
  outline: none;
  padding: 16px;
  min-height: 100px;
  line-height: 1.6;
  font-family: inherit;
  border-radius: 12px;
  margin-bottom: 10px;
}

.search-button {
  position: absolute;
  right: 10px;
  bottom: 10px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
}

.search-button:hover {
  background: #45a049;
}

.tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
  margin-bottom: 30px;
}

.tab-button {
  padding: 8px 18px;
  border: none;
  border-radius: 999px;
  font-size: 14px;
  background-color: #e0e0e0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.tab-button:hover {
  background-color: #d0d0d0;
}

.tab-button.active {
  background-color: black;
  color: white;
}

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 20px;
}

.card {
  background-color: white;
  border: 1px solid #e5e5e5;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.2s ease;
}

.card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.card-text {
  margin-bottom: 16px;
  color: #333;
}

.card-source {
  font-size: 14px;
  color: #888;
}

.loading,
.no-result {
  font-size: 16px;
  color: #666;
  text-align: center;
  padding: 40px 0;
}

.status-sidebar {
  width: 300px;
  position: sticky;
  top: 40px;
  height: fit-content;
  background: white;
  border-radius: 24px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.task-status-header {
  background: white;
  padding: 20px;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.task-count {
  font-size: 14px;
  color: #666;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 12px;
}

.task-list {
  padding: 20px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.task-item {
  background-color: #f8f9fa;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.task-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.task-active {
  border-left: 4px solid #4CAF50;
}

.task-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.delete-task {
  background: none;
  border: none;
  color: #999;
  font-size: 20px;
  cursor: pointer;
  padding: 0 5px;
  line-height: 1;
}

.delete-task:hover {
  color: #f44336;
}

.task-description {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.task-details {
  font-size: 12px;
  color: #666;
}

.task-details p {
  margin: 4px 0;
}

.no-tasks {
  text-align: center;
  color: #999;
  padding: 20px;
  font-size: 14px;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background-color: #e0e0e0;
  border-radius: 3px;
  margin-top: 15px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.3s ease;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .app-container {
    grid-template-columns: 1fr;
    padding: 20px;
  }

  .status-sidebar {
    width: 100%;
    position: static;
    margin-top: 20px;
  }

  .task-list {
    max-height: none;
  }
}
</style>
